package edu.nju.cineplex.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import edu.nju.cineplex.dao.DaoHelper;
import edu.nju.cineplex.dao.SaleDao;
import edu.nju.cineplex.factory.DaoFactory;
import edu.nju.cineplex.model.Sale;

public class SaleDaoImpl implements SaleDao {
	private static SaleDaoImpl saleDao = new SaleDaoImpl();
	private static DaoHelper daoHelper = DaoHelperImpl.getBaseDaoInstance();

	private SaleDaoImpl() {

	}

	public static SaleDao getInstance() {
		return saleDao;
	}

	@Override
	public void addSale(Sale sale) {
		// TODO Auto-generated method stub
		Connection con = daoHelper.getConnection();
		PreparedStatement stmt = null;
		try {
			stmt = con
					.prepareStatement("insert into sale(uId,tId,createDate) values(?,?,curdate())");
			stmt.setLong(1, sale.getUser().getId());
			stmt.setLong(2, sale.getTimetable().getId());
			stmt.executeUpdate();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			daoHelper.closePreparedStatement(stmt);
			daoHelper.closeConnection(con);
		}
	}

	@Override
	public List<Sale> findByUserId(long id) {
		// TODO Auto-generated method stub
		Connection con = daoHelper.getConnection();
		PreparedStatement stmt = null;
		ResultSet result = null;
		List<Sale> saleList = new ArrayList<Sale>();
		try {
			stmt = con.prepareStatement("select * from sale where uId = ?");
			stmt.setLong(1, id);
			result = stmt.executeQuery();
			while (result.next()) {
				Sale sale = new Sale();
				sale.setId(result.getLong(1));
				sale.setUser(DaoFactory.getUserDao().findById(id));
				sale.setTimetable(DaoFactory.getTimetableDao()
						.findById(result.getLong(3)));
				sale.setCreateDate(result.getDate(4));
				saleList.add(sale);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			daoHelper.closeResultSet(result);
			daoHelper.closePreparedStatement(stmt);
			daoHelper.closeConnection(con);
		}
		return saleList;
	}

}
